<cfcomponent extends="Controller" output="false">
	
	<!--- -fixtures/index --->
	<cffunction name="index">
		<cfset fixtures = model("Fixture").findAll()>
	</cffunction>
	
	<cffunction name="generateDatesHelper">
		<cfsavecontent variable="data">
			<cfset xmas = "{ts '2010-12-25 00:00:00'}">
			<cfdump var="#Week(xmas)#">
			
			<cfset tmp = getFixtureDates(6,now(),'52,53,1,2')>
			
			<cfdump var="#tmp#">
			<cfdump var="#tmp[ArrayLen(tmp)]#" label="y">
		</cfsavecontent>
		<cfset renderPage(template="/shared/singleOutput")>
	</cffunction>
		
	<cffunction name="getFixtureDates" hint="Generates a bunch of dates into an array">
		<cfargument name="NoRounds" type="numeric" required="true" default="">
		<cfargument name="StartDate" type="date" required="true" default="">
		<cfargument name="skipWeeks" type="string" required="false" default="">
		<cfscript>
			var loc = {};
			
			loc.skipWeeks = "{ts '2010-12-25 00:00:00'},{ts '2011-01-01 00:00:00'}";			
			if(Len(arguments.skipWeeks))
			{
				loc.skipWeeks = arguments.skipWeeks;
			}
			
			loc.NoRounds = "10";
			if(Len(arguments.NoRounds))
			{
				loc.NoRounds = arguments.NoRounds;
			}
			
			loc.StartDate = '2010-11-13';
			if(Len(arguments.StartDate))
			{
				loc.StartDate = arguments.StartDate;
			}
			
			loc.dayOfWeek = DayOfWeek(loc.StartDate);
			loc.rounds = ArrayNew(1);
			loc.roundDate = loc.StartDate;
			
			for (i=1; i LTE 10;)
			{	
				if(ListFind(loc.skipWeeks,Week(loc.roundDate)))
				{
					// Skip the week
				}
				else
				{
					loc.rounds[i] = loc.roundDate;
					i=i+1;
				}
				// Add 7 days 
				loc.roundDate = DateAdd("ww",1,loc.roundDate);
			}
		</cfscript>		
		<cfreturn loc.rounds>
	</cffunction>
	
	<cffunction name="generate" hint="Generates the fixtures for a season">
		
		<cfset var loc = {}>
		
		<cfset season = model("Season").findByKey(params.key)>
		<cfif NOT isObject(season)>
			<cfset flashInsert(error="Season not found")>
			<cfset redirectTo(back=true)>
		</cfif>
		
		<cfset seasonTeams = model("Team").findAll(select="TeamID,TeamName",where="SeasonID='#season.seasonID#'")>
		<cfif seasonTeams.recordCount>
			<cfset seasonTeamIds = ValueList(seasonTeams.TeamID)>		
			<cfset seasonTeamNames = ValueList(seasonTeams.TeamName)>
		</cfif>
		
		<cfset loc.noRounds = 10>
		<cfif Len(season.noRounds)>
			<cfset loc.noRounds = season.noRounds>
		</cfif>
		
		<cfset loc.skipWeeks = "{ts '2010-12-25 00:00:00'},{ts '2011-01-01 00:00:00'}">		
		<cfif Len(season.skipWeeks)>
			<cfset loc.skipWeeks = season.skipWeeks>
		</cfif>
		
		<cfset loc.StartDate = '2010-11-13'>
		<cfif Len(season.StartDate)>
			<cfset loc.StartDate = season.StartDate>
		</cfif>
		
		
		
		<cfset loc.dayOfWeek = DayOfWeek(loc.StartDate)>
		
		
		
		<!--- Pass in the array of teams --->
		
		<cfset loc.teams = ArrayNew(1)>
		<cfset j = 1>
		<cfloop list="#seasonTeamIds#" index="i">
			<cfset loc.teams[j] = {}>
			<cfset loc.teams[j]['ID'] = i>
			<cfset loc.teams[j]['Name'] = ListGetAt(seasonTeamNames,j)>
			<cfset j = j+1>
		</cfloop>		
	
		
		<cfset loc.totalRounds = ArrayLen(loc.teams) - 1>
		<cfset loc.matchesPerRound = ArrayLen(loc.teams) / 2>
		<cfset loc.totalTeams = ArrayLen(loc.teams)>
		<cfset loc.rounds = ArrayNew(1)>
		<cfset loc.roundDates = getFixtureDates(loc.noRounds,loc.StartDate,loc.skipWeeks)>
		<cfloop from="1" to="#loc.totalRounds#" index="i">
			<cfset loc.rounds[i] = ArrayNew(1)>
		</cfloop>
		
		<cfloop from="1" to="#loc.totalRounds#" index="round">
			<cfloop from="1" to="#loc.matchesPerRound#" index="match">
							
				<cfset home = ((round-1) + (match-1)) MOD (loc.totalTeams - 1)>
				<cfset away = ((loc.totalTeams - 1) - (match-1) + (round-1)) MOD (loc.totalTeams -1)>				
				
				<!--- Last team stays in the same place while the others rotate around it --->
				<cfif match EQ 1>
					<cfset away = loc.totalTeams - 1>
				</cfif>
				<cfset loc.rounds[round][match] = home+1 & " vs " & away+1>				
			</cfloop>
		</cfloop>
		
		
		<cfset loc.interleaved = ArrayNew(1)>
		<cfloop from="1" to="#loc.totalRounds#" index="i">
			<cfset loc.interleaved[i] = ArrayNew(1)>
		</cfloop>
		
		<cfset evn = 1>
		<cfset odd = (loc.totalTeams / 2) + 1>
		<cfloop from="1" to="#ArrayLen(loc.rounds)#" index="i">
			<cfif i MOD 2 EQ 1>		
				<cfset loc.interleaved[i] = loc.rounds[evn]>
				<cfset evn = evn + 1>					
			<cfelse>
				
				<cfset loc.interleaved[i] = loc.rounds[odd]>	
				<cfset odd = odd + 1>			
			</cfif>
		</cfloop>
		
		<cfset loc.rounds = loc.interleaved>
		<cfset loc.interleaved = 0>
		
		
		<!--- Last team can't be away for every game so flip them --->
		<cfloop from="1" to="#ArrayLen(loc.rounds)#" index="round">		
			<cfif round MOD 2 EQ 0>				
				<cfset loc.rounds[round][1] = flip(loc.rounds[round][1])>
			</cfif>
		</cfloop>
		
		
		
		
		<cfset roundCount = 1>		
		<cfloop array="#loc.rounds#" index="rnd">
			<cfloop array="#rnd#" index="match">
				<cfset roundDetails = {}>
				<cfset roundDetails['No'] = roundCount>
				<cfset roundDetails['Date'] = loc.RoundDates[roundCount]>
				<cfset addFixtureDetails(season.seasonID,roundDetails,loc.teams[ListFirst(match,' vs ')],loc.teams[ListLast(match,' vs ')])>
			</cfloop>	
			<cfset roundCount = roundCount + 1>
		</cfloop>
				
		<!--- Need to try append the other half of the season before looping through and adding all the entries --->
		<cfset roundCount = 1>
		<cfloop array="#loc.rounds#" index="rnd">			
			<cfloop array="#rnd#" index="match">				
				<cfset altMatch = flip(match)>
				<cfset altRoundCount = roundCount+(loc.totalTeams-1)>
				
				<cfset roundDetails = {}>
				<cfset roundDetails['No'] = altRoundCount>
				<cfset roundDetails['Date'] = loc.RoundDates[altRoundCount]>
				<cfset addFixtureDetails(season.seasonID,roundDetails,loc.teams[ListFirst(altMatch,' vs ')],loc.teams[ListLast(altMatch,' vs ')])>
			</cfloop>
			<cfset roundCount = roundCount + 1>
		</cfloop>
		
			
		<!--- Set Fixture timestamp to Season --->
		<cfset season.EndDate = loc.roundDates[ArrayLen(loc.roundDates)]>
		<cfset season.FixtureCreated = now()>
		<cfset season.save()>
		<cfif season.hasErrors()>
			<cfdump var="An error occurred">
			<cfabort>
		</cfif>
		
		
		<cfset redirectTo(controller="seasons",action="show",key="#season.seasonID#")>
		
	</cffunction>
	
	<cffunction name="addFixtureDetails" hint="Pass in all the details for a new fixture">
		<cfargument name="SeasonID" type="numeric">
		<cfargument name="Round" type="struct">
		<cfargument name="HomeTeam" type="struct">
		<cfargument name="AwayTeam" type="struct">
		
		<cfset var result = ''>
		<cfset fixture = model("Fixture").new()>
		<cfset fixture.SeasonID = arguments.SeasonID>
		<cfset fixture.RoundNo = arguments.Round.No>
		<cfset fixture.RoundDate = arguments.Round.Date>
		<cfset fixture.HomeTeamID = arguments.HomeTeam.ID>
		<cfset fixture.HomeTeamName = arguments.HomeTeam.Name>
		<cfset fixture.AwayTeamID = arguments.AwayTeam.ID>
		<cfset fixture.AwayTeamName = arguments.AwayTeam.Name>
		<cfset result = fixture.save()>
		<cfif fixture.hasErrors()>
			<cfdump var="An error occurred">
			<cfabort>
		</cfif>
		<cfreturn result>
	</cffunction>
		
	<cffunction name="flip">
		<cfargument name="str">				
		<cfreturn ListLast(str,' vs ') & ' vs ' & ListFirst(str,' vs ')>
	</cffunction>
	
	
	<cffunction name="deleteSeasonFixtures" hint="Deletes all the fixtures for a season">
		<!--- delete all the fixtures --->
		<cfset fixtures = model("Fixture").deleteAll(where="SeasonId='#params.key#'")>
		
		<!--- set the fixtureCreated to null --->
		<cfset season = model("Season").findByKey(params.key)>
		<cfset season.FixtureCreated = ''>
		<cfset season.EndDate = ''>
		<cfset season.save()>
		<cfif season.hasErrors()>
			<cfdump var="An error occurred">
			<cfabort>
		</cfif>
		
		<cfset flashInsert(success="Deleted all (#fixtures#) fixtures")>
		<cfset redirectTo(back=true)>
	</cffunction>
	

	
	<!--- -fixtures/show/key --->
	<cffunction name="show">
		
		<!--- Find the record --->
    	<cfset fixture = model("Fixture").findByKey(params.key)>
		
		<cfset homeTeam = model("Team").findByKey(fixture.HomeTeamID)>
		<cfset awayTeam = model("Team").findByKey(fixture.AwayTeamID)>
    	
    	<!--- Check if the record exists --->
	    <cfif NOT IsObject(fixture)>
	        <cfset flashInsert(error="Fixture #params.key# was not found")>
	        <cfset redirectTo(action="index")>
	    </cfif>
			
	</cffunction>
		
	<!--- -fixtures/new --->
	<cffunction name="new">
		<cfset fixture = model("Fixture").new()>
	</cffunction>
	
	<!--- -fixtures/edit/key --->
	<cffunction name="edit">
	
		<!--- Find the record --->
    	<cfset fixture = model("Fixture").findByKey(params.key)>
    	
    	<!--- Check if the record exists --->
	    <cfif NOT IsObject(fixture)>
	        <cfset flashInsert(error="Fixture #params.key# was not found")>
			<cfset redirectTo(action="index")>
	    </cfif>
		
	</cffunction>
		
	
	<!--- -fixtures/create --->
	<cffunction name="create">
		<cfset fixture = model("Fixture").new(params.fixture)>
		
		<!--- Verify that the fixture creates successfully --->
		<cfif fixture.save()>
			<cfset flashInsert(success="The fixture was created successfully.")>
            <cfset redirectTo(action="index")>
		<!--- Otherwise --->
		<cfelse>
			<cfset flashInsert(error="There was an error creating the fixture.")>
			<cfset renderPage(action="new")>
		</cfif>
	</cffunction>
	
	<!--- -fixtures/update --->
	<cffunction name="update">
		<cfset fixture = model("Fixture").findByKey(params.key)>
		
		<!--- Verify that the fixture updates successfully --->
		<cfif fixture.update(params.fixture)>
			<cfset flashInsert(success="The fixture was updated successfully.")>	
            <cfset redirectTo(action="index")>
		<!--- Otherwise --->
		<cfelse>
			<cfset flashInsert(error="There was an error updating the fixture.")>
			<cfset renderPage(action="edit")>
		</cfif>
	</cffunction>
	
	<!--- -fixtures/delete/key --->
	<cffunction name="delete">
		<cfset fixture = model("Fixture").findByKey(params.key)>
		
		<!--- Verify that the fixture deletes successfully --->
		<cfif fixture.delete()>
			<cfset flashInsert(success="The fixture was deleted successfully.")>	
            <cfset redirectTo(action="index")>
		<!--- Otherwise --->
		<cfelse>
			<cfset flashInsert(error="There was an error deleting the fixture.")>
			<cfset redirectTo(action="index")>
		</cfif>
	</cffunction>
	
</cfcomponent>
